import path from 'path';
import fs from 'fs';
import Api from '../request/api.js';
import { sleep, log, md5, getHallId, timeFormat } from '../utils/utils.js';
import process from 'process';
import dotenv from 'dotenv';
import puppeteer from 'puppeteer-extra';
import axios from 'axios';
import { PayType, TicketChannel } from '../constant/index.js';

const ua =
  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36 MicroMessenger/6.8.0(0x16080000) NetType/WIFI MiniProgramEnv/Mac MacWechat/WMPF XWEB/30626';

// const waitSelectTime = 300000; // 选座等待时间
dotenv.config();
const {
  EXECUTABLE_PATH,
  CINEMA_ACC_ID,
  CINEMA_TOKEN = '',
  CINEMA_ACCOUNT,
  CINEMA_CITYCODE,
  CINEMA_PWD,
  CINEMA_LINKID,
  CINEMA_CODE,
} = process.env;

const API = new Api();

export default class HappinessApp {
  // token
  loginToken = CINEMA_TOKEN;

  // 用户信息
  ticketUser = {};

  // 会员卡信息
  memberCardInfo = null;

  // 会员卡成本
  prePayCardinfo = null;

  // 订单选择支付方式
  doPayType = 2; // 默认会员卡

  // 座位
  selectSeatList = '';

  // 接口请求头
  requestHeader = {
    'User-Agent': ua,
    Accept: 'application/json',
    'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'Content-Type': 'application/x-www-form-urlencoded',
    'gray-lease-code': 'GS',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-site',
    Pragma: 'no-cache',
    'Cache-Control': 'no-cache',
  };

  // 订单信息
  order = {
    state: '',
    ticketCode: '',
    paramDetail: {}, // 订单详情参数
  };

  // 锁定订单ID
  lockOrderId = '';

  // 创建订单ID
  orderConfirmId = '';

  // data
  dataJson = null;

  // 写入本地保存
  setOrderState(state, ticketCode = '', paramDetail = {}) {
    if (ticketCode) {
      this.order.ticketCode = ticketCode;
    }
    this.order.paramDetail = { ...this.order.paramDetail, ...paramDetail };
    this.order.state = state;

    fs.writeFileSync(
      './orderJson/' + this.dataJson.sn + '.json',
      JSON.stringify(this.order, null, 2),
      {
        flag: 'w',
      },
      (err) => {
        if (err) {
          console.error('订单状态写入', err);
        }
      }
    );
  }

  // 订单开始 初始化
  async orderStart(dataJson) {
    // 检查登录
    this.ticketUser = {
      cinemaAccId: CINEMA_ACC_ID,
      cinemaAccount: CINEMA_ACCOUNT,
      cinemaAccountPwd: CINEMA_PWD,
    };

    this.order = {
      state: '',
      ticketCode: '',
      paramDetail: {},
    };
    this.dataJson = dataJson;
    this.selectSeatList = null;
    this.memberCardInfo = null;
    this.orderConfirmId = '';
    this.lockOrderId = '';
  }

  // 获取座位信息
  async getSeat() {
    // 等待选座
    const dataJson = this.dataJson;
    const { scheduleKey } = dataJson.showObj;
    const resData = await this.requestPageApi(
      'app/seat/getChannelPlanSeat',
      {
        channelPlanCode: scheduleKey,
      },
      'POST'
    );
    if (
      !resData.channelPlanSeatList ||
      resData.channelPlanSeatList.length === 0
    ) {
      log('场次数据获取失败 ' + JSON.stringify(resData), 'error');
      throw new Error('场次选择失败');
    }

    // const { play_date, start_time } = resData.play_data;
    //  "play_date": "2023-07-12",
    //  "start_time": "15:20:00",
    // 判断时间是否正确
    // const showTime = new Date(`${play_date} ${start_time}`);
    // if (showTime.getTime() !== dataJson.showTimestamp) {
    //   throw new Error('场次选择失败[RETRY]');
    // }

    // 订单座位
    // 座位转成 [[11,2],[11,3]]
    const seatListArr = this.dataJson.seatList.map((i) =>
      i
        .match(/[\d|A-Za-z]+/g)
        .map((d) => (isNaN(Number(d)) ? d.toLocaleUpperCase() : String(d)))
    );
    // const seatListArr = dataJson.seatList;
    // 获取座位
    const seatList = [];
    // {"cinemaCode":"31195901","salePrice":59.90,"screenCode":"0000000000000002","screenName":null,"seatCode":"3119590102#06#08","groupCode":"avCYuacVm5U1srOq","rowNum":"6","columnNum":"8","seatLevel":"1868293529869058049","seatStatus":"Booked","priceInfo":{"level":"1868293529869058049","marketingCode":null,"marketingName":null,"cinemaAllowance":null,"standardPrice":52.26,"lowestPrice":40.00,"serviceAddFee":3.14,"channelPrice":55.40,"salePrice":59.90,"minMemberPrice":59.90,"minMemberActivityPrice":59.90,"minActivityPrice":59.90},"memberPriceList":null,"channelPrice":55.40,"minMemberPrice":59.90,"minMemberActivityPrice":59.90,"minActivityPrice":59.90,"ycoord":"6","xcoord":"11"}
    for (const seat of resData.channelPlanSeatList) {
      if (
        !seatListArr.find(
          (st) => st[0] === seat.rowNum && st[1] === seat.columnNum
        )
      ) {
        continue;
      }

      if (seat.seatStatus !== 'Available') {
        throw new Error(
          `座位已被锁定 ${this.dataJson.from} ${this.dataJson.cinemaName}`
        );
      }

      seatList.push({
        sectionNo: seat.seatCode,
        seatName: seat.groupCode,
        row: seat.rowNum,
        col: seat.columnNum,
      });
    }
    if (seatList.length < dataJson.seatList.length) {
      throw new Error('座位未找到');
    }

    this.selectSeatList = seatList;
    return seatList;
  }

  // 锁定座位
  /**
   * [{"areaId":"0","column":3,"columnName":"2","flag":0,"name":"1排2座","row":1,"rowName":"1","seatId":"000000031026-1-3","status":1}]
   */
  async lockSeat() {
    const seatList = this.selectSeatList;
    const dataJson = this.dataJson;
    const { scheduleKey } = dataJson.showObj;
    // 座位锁定请求
    const lockBizData = await this.requestPageApi(
      'app/seat/lockSeat',
      {
        seatCodes: seatList.map((s) => s.sectionNo),
        channelPlanCode: scheduleKey,
      },
      'POST'
    );
    if (lockBizData && lockBizData.orderNo) {
      // 成功锁座
      log('座位锁定成功');
      this.lockOrderId = lockBizData.orderNo;
    } else {
      // 锁座失败
      log('座位锁定请求失败 ' + JSON.stringify(lockBizData), 'error');
      throw new Error('锁座失败[RETRY]:' + (lockBizData.msg || ''));
    }
  }

  // 提交订单信息
  async submitOrderInfo(cinemaInfo) {
    const selectSeatList = this.selectSeatList;
    // 获取支付信息
    const preparePaymentInfo = await this.requestPageApi(
      'app/order/preparePaymentByOnline',
      {
        mainOrderNo: this.lockOrderId,
      },
      'POST'
    );

    // 支付方式
    let payType;
    let vipCard;
    let costFee = 999999;
    if (cinemaInfo.settle_type == PayType.BALANCE) {
      if (!preparePaymentInfo.usableCards) {
        throw new Error('VIP卡获取失败');
      }
      vipCard =
        preparePaymentInfo.usableCards.reduce(
          (max, item) => (item.balance > max.balance ? item : max),
          preparePaymentInfo.usableCards[0]
        ) || {};
      // 获取可用VIP-CARD
      ({ payType, costFee } = await this.getVipCost(vipCard, cinemaInfo));
    } else if (cinemaInfo.settle_type == PayType.COUPON) {
      ({ payType, costFee } = this.getCouponCost(cinemaInfo));
    } else {
      // 根据成本 选择支付方式
      if (cinemaInfo.vip_cost_ratio > 0) {
        // VIP
        if (!preparePaymentInfo.usableCards) {
          throw new Error('VIP卡获取失败');
        }
        vipCard =
          preparePaymentInfo.usableCards.reduce(
            (max, item) => (item.balance > max.balance ? item : max),
            preparePaymentInfo.usableCards[0]
          ) || {};
        ({ payType, costFee } = await this.getVipCost(vipCard, cinemaInfo));
      }
      if (cinemaInfo.coupon_fee > 0) {
        // 抵扣券
        const { payType: pt, costFee: vipCostFee } =
          this.getCouponCost(cinemaInfo);
        if (vipCostFee < costFee) {
          costFee = vipCostFee;
          payType = pt;
        }
      }
    }

    // 更新成本
    // log('更新成本 ' + JSON.stringify({ costFee, payType }));
    await API.updateOrderCost(this.dataJson.id, costFee || 999999);
    const sellAmount = Number(this.dataJson.sellAmount);
    // force_ticket是否强制出票
    if (sellAmount > 0 && sellAmount <= costFee && !cinemaInfo.force_ticket) {
      throw new Error(
        `成本高于报价[类型${payType}-成本${costFee}-报价${sellAmount}]`
      );
    }

    // throw new Error('支付拦截 ' + costFee + ' ' + payType);
    // return;

    // 开始进行支付
    let payResult = false;
    if (payType === PayType.BALANCE) {
      // 余额判定
      if (Number(vipCard.balance) < costFee) {
        throw new Error('会员卡余额不足');
      }
      // 使用会员卡余额
      payResult = await this.useVipBalance(cinemaInfo, vipCard);

      // 更新余额
      await API.updateVipBalance(
        (vipCard.balance - this.prePayCardinfo.salePrice).toFixed(2),
        vipCard.id,
        vipCard.cardName || '会员卡X'
      ).catch((e) => {
        log('更新会员卡余额失败：' + JSON.stringify(e));
      });
    } else if (payType === PayType.COUPON) {
      if (!preparePaymentInfo.usableCoupons) {
        throw new Error('抵扣券获取失败');
      }
      // 使用抵扣券
      payResult = await this.useCoupon(
        preparePaymentInfo.usableCoupons.filter(
          (c) => c.couponStatus == '1' && c.available
        )
      );
    }
    if (!payResult) {
      throw new Error('支付失败-' + payType);
    }
    // 设置订单状态
    this.setOrderState('success', '', {
      costFee,
      payType,
      orderId: this.orderConfirmId,
    });

    await sleep(2000);
    // 从订单列表里获取订单信息
    return this.getOrderInfo();
  }

  // 获取会员卡信息
  async getCardInfo(selectSeatList) {
    if (this.memberCardInfo) {
      return this.memberCardInfo;
    }
    const dataJson = this.dataJson;
    const { scheduleKey } = dataJson.showObj;
    const requestParams = {
      additional_goods_info: '',
      goods_info: '',
      is_first: '1',
      option_goods_info: '',
      seat_ids: selectSeatList.map((s) => s.sectionNo).join(','),
      show_id: scheduleKey,
      update_time: '',
    };

    // 获取会员卡列表
    let cardBal = 0;
    const cardList = await this.requestPageApi('card/get-user-cinema-card', {});
    if (cardList && cardList.card_data && cardList.card_data.length > 0) {
      for (const card of cardList.card_data) {
        if (card.card_status === '1' && Number(card.balance) > cardBal) {
          requestParams.is_first = '0';
          requestParams.card_id = card.id;
          cardBal = Number(card.balance);
        }
      }
    }

    let calData = await this.requestPageApi(
      'v2/price/calculate',
      requestParams,
      'POST'
    );
    if (calData.errcode === '400005') {
      // 本卡在该影院下不可用
      requestParams.is_first = '1';
      delete requestParams.card_id;
      calData = await this.requestPageApi(
        'v2/price/calculate',
        requestParams,
        'POST'
      );
    }

    this.memberCardInfo =
      calData.price || calData.defaultCardPrice || calData.nonMemberPrice;
    log('获取会员卡 memberCardInfo值 ' + JSON.stringify(this.memberCardInfo));
    return this.memberCardInfo;
  }

  // VIP成本
  async getVipCost(vipCard, cinemaInfo) {
    // VIP
    this.prePayCardinfo = await this.requestPageApi(
      'app/order/preparePaymentByCard',
      { mainOrderNo: this.lockOrderId, cardNo: vipCard.id },
      'POST'
    );
    if (!this.prePayCardinfo || !this.prePayCardinfo.id) {
      throw new Error('VIP成本获取失败 ' + JSON.stringify(this.prePayCardinfo));
    }

    if (this.prePayCardinfo.dealPrice > 0) {
      throw new Error('VIP需要额外支付金额: ' + this.prePayCardinfo.dealPrice);
    }

    return {
      payType: PayType.BALANCE,
      costFee:
        this.prePayCardinfo.salePrice * cinemaInfo.vip_cost_ratio +
          this.prePayCardinfo.dealPrice || 999999,
    };
  }

  // 抵扣券成本
  getCouponCost(cinemaInfo) {
    // 抵扣券
    const ticketCount = this.dataJson.seatList.length;
    const { isSpec, weight, couponPlus = 0 } = this.dataJson.showObj;
    let costFee = cinemaInfo.coupon_fee * ticketCount;
    if (isSpec) {
      costFee = cinemaInfo.coupon_fee * weight * ticketCount + couponPlus;
    }
    return {
      payType: PayType.COUPON,
      costFee,
    };
  }

  // 使用抵扣券
  async useCoupon(couponListData) {
    // 更新券数
    let useCouponNum = this.dataJson.seatList.length;
    const { isSpec, weight } = this.dataJson.showObj;
    if (isSpec) {
      // 特殊影厅
      useCouponNum = useCouponNum * weight;
    }
    const totalNeedCouponNum = useCouponNum;
    if (couponListData.length < useCouponNum) {
      throw new Error(
        `抵扣券数量不足[${couponListData.length}-${useCouponNum}]`
      );
    }
    // 查找使用抵扣券
    const ticketInfos = [];
    for (const couponInfo of couponListData) {
      if (useCouponNum <= 0) {
        break;
      }
      if (!couponInfo.available || couponInfo.couponStatus !== '1') {
        continue;
      }

      ticketInfos.push(couponInfo);
      useCouponNum = useCouponNum - 1;
    }
    if (ticketInfos.length < totalNeedCouponNum) {
      throw new Error(
        `抵扣券可用的券数不足[${ticketInfos.length}-${totalNeedCouponNum}]`
      );
    }

    // 验证抵扣券
    const quanCodes = ticketInfos.map((t) => t.id);
    const validatorData = await this.requestPageApi(
      'app/order/preparePaymentByCoupon',
      {
        mainOrderNo: this.lockOrderId,
        couponList: quanCodes,
        goodsCoupons: [],
      },
      'POST'
    );
    if (!validatorData) {
      throw new Error('验券失败[TRY]');
    }
    if (validatorData.dealPrice > 0) {
      throw new Error('抵扣券需要额外支付金额:' + validatorData.dealPrice);
    }

    // 创建订单
    this.doPayType = 3;
    const orderInfo = await this.payOrder();

    // 更新券列表
    await API.uploadCoupon(
      couponListData
        .filter((i) => !quanCodes.includes(i.id))
        .map((coupon) => ({
          type: 1,
          couponNo: coupon.id,
          status: coupon.couponStatus === '1' ? 1 : 2,
          timeStart: new Date(coupon.beginTime).getTime() / 1000,
          timeEnd: new Date(coupon.endTime).getTime() / 1000,
          couponVer: coupon.couponCategoryId,
          couponName: coupon.couponCategoryName || '',
          couponInfo: coupon.couponName || '',
        })),
      CINEMA_ACC_ID,
      CINEMA_ACCOUNT,
      TicketChannel.HAPPINESS
    );

    await API.updateCouponNum(couponListData.length - useCouponNum);

    this.orderConfirmId = orderInfo.mainOrderNo;
    return true;
  }

  async payOrder() {
    // 创建订单
    const confirmTicketOrder = await this.requestPageApi(
      'app/order/confirmTicketOrder?mainOrderNo=' + this.lockOrderId
    );
    if (confirmTicketOrder) {
      throw new Error('确认出接口失败:' + confirmTicketOrder.msg);
    }

    // 执行兑换/支付
    const exchangeData = await this.requestPageApi(
      'app/pay/prePay/v2',
      {
        mainOrderNo: this.lockOrderId,
        payAgentType: this.doPayType,
      },
      'POST'
    );
    if (!exchangeData || !exchangeData[0]) {
      log('执行支付失败：' + JSON.stringify(exchangeData));
      throw new Error('执行支付失败[TRY] ' + (exchangeData.msg || ''));
    }
    return exchangeData[0];
  }

  // 使用VIP余额支付
  async useVipBalance(cinemaInfo, defaultCard) {
    // 创建订单
    const checkRes = await this.requestPageApi(
      'app/order/checkCardPassword',
      {
        cardId: defaultCard.id,
        password: cinemaInfo.vip_pwd,
      },
      'POST'
    );
    if (checkRes) {
      log('会员卡支付失败：' + JSON.stringify(checkRes));
      throw new Error('会员卡支付失败[TRY]：' + (checkRes.msg || ''));
    }

    const orderInfo = await this.payOrder();
    this.orderConfirmId = orderInfo.mainOrderNo;
    return orderInfo;
  }

  // 获取订单信息
  async getOrderInfo(retryTimes = 1) {
    const filePath = './orderJson/' + this.dataJson.sn + '.json';
    if (!fs.existsSync(filePath)) {
      return false;
    }
    const buffer = fs.readFileSync(filePath);
    const fileContent = buffer.toString();
    if (!fileContent) {
      return false;
    }
    const orderState = JSON.parse(fileContent);
    this.order = orderState;

    const orderDetailData = await this.requestPageApi(
      'app/order/queryOrder',
      {
        mainOrderNo: orderState.paramDetail.orderId,
      },
      'POST'
    );
    if (!orderDetailData || orderDetailData.orderStatus === 2) {
      if (retryTimes < 3) {
        await sleep(5000);
        return await this.getOrderInfo(retryTimes + 1);
      }
      throw new Error('获取订单详情失败[RETRY] ' + (orderDetailData.msg || ''));
    }
    if (!orderDetailData.qrCode) {
      if (retryTimes < 3) {
        await sleep(5000);
        return await this.getOrderInfo(retryTimes + 1);
      }
      throw new Error('等待获取二维码[RETRY]:' + (orderDetailData.msg || ''));
    }

    let uploadLink = '';
    if (this.dataJson.screenshot) {
      // 上传截图
      uploadLink = await this.screenshotAndUpload(orderDetailData);
    }
    let ticketCode = orderDetailData.qrCode;

    this.setOrderState('success', ticketCode);

    return {
      orderId: orderDetailData.mainOrderNo,
      payType: orderState.paramDetail.payType,
      ticketCode,
      uploadLink,
    };
  }

  // 截图上传
  async screenshotAndUpload(detail) {
    const sep = path.sep;
    const ticketOrder = detail.ticketOrder;
    const startTimeArr = ticketOrder.showTime.split(' ');
    const data = {
      mobile: detail.userMobile,
      order_num: detail.totalCount,
      movie_name: ticketOrder.filmName,
      movie_img_url: 'https://ticket-app.heqixin.net' + ticketOrder.filmPoster,
      cinema_name: ticketOrder.cinemaName,
      hall_name: ticketOrder.screenName,
      seat_info: ticketOrder.seatInfo,
      start_date: startTimeArr[0],
      start_time: startTimeArr[1],
      create_time: ticketOrder.ticketTime,
      movie_format: ticketOrder.showTypeName,
      msg: ticketOrder.ticketStatusName,
      total_price: ticketOrder.totalOrderPrice,
      serial_number_1: detail.qrCode,
      serial_number_2: '',
      qrcode: detail.qrCode.replace('|', ''),
      ticket_code_type: '0',
      seats: ticketOrder.seatInfo,
      message: '',
      tel: '',
    };
    // 本地路径
    const url = `file://${path.resolve(
      './'
    )}${sep}html${sep}order-detail.html?data=${encodeURIComponent(
      JSON.stringify(data)
    )}`;
    // 初始化
    const browser = await puppeteer.launch({
      executablePath: EXECUTABLE_PATH,
      //设置超时时间
      timeout: 15000,
      ignoreHTTPSErrors: true,
      headless: true,
      args: ['--disable-dev-shm-usage', '--no-sandbox', '--disable-plugins'],
    });
    const page = await browser.newPage();
    await page.goto(url);
    await page.setViewport({
      width: 375,
      height: 590,
    });

    await sleep(500);
    // 截图
    const screenshotPath = './screenshot/' + this.dataJson.sn + '.png';
    await page.screenshot({
      path: screenshotPath,
    });
    await browser.close();

    // 上传截图
    return await API.uploadScreenshot(screenshotPath);
  }

  // 订单取消
  async cancelOrder() {
    if (this.orderConfirmId) {
      // 解锁请求
      return await this.requestPageApi(
        'app/order/card/closeOrder',
        {
          mainOrderNo: this.orderConfirmId,
        },
        'POST'
      );
    }
    return true;
  }

  // 解锁座位
  async unlockSeat() {
    if (this.lockOrderId) {
      // 解锁请求
      return await this.requestPageApi(
        'app/seat/releaseSeat',
        {
          orderNo: this.lockOrderId,
        },
        'POST'
      );
    }
    return true;
  }

  // 页面接口请求
  async requestPageApi(path, data = {}, method = 'GET') {
    let url = `https://ticket-app.heqixin.net/${path}`;
    // 拼接url
    url = url.includes('?')
      ? url + '&channelType=WX_XFKDY&deviceType=android'
      : url + '?channelType=WX_XFKDY&deviceType=android';

    // 设置影院ID;
    let requestParams = {
      ...data,
    };

    let requestBody = '';
    let header = {};
    if (method.toLocaleUpperCase() === 'POST') {
      requestBody = JSON.stringify(requestParams);
      header = {
        'Content-Type': 'application/json',
      };
    }
    const res = await axios
      .request({
        url,
        method,
        data: requestBody,
        timeout: 15000,
        headers: {
          Authorization: 'Bearer ' + this.loginToken,
          'user-agent':
            'Mozilla/5.0 (Linux; Android 15; 24129PN74C Build/AQ3A.240812.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0.6778.260 Mobile Safari/537.36 uni-app Html5Plus/1.0 (Immersed/36.923077)',
          Host: 'ticket-app.heqixin.net',
          Connection: 'close',
          'Accept-Encoding': 'gzip, deflate',
          ...header,
        },
      })
      .catch((e) => {
        log(
          `幸福请求接口[${url}]异常 ${JSON.stringify(
            requestBody
          )} ${JSON.stringify(e)}`,
          'error'
        );
        return {
          status: -2, // 超时
          data: {
            status: -101,
            msg: e.message,
          },
        };
      });
    if (!res.data || res.data.code != 200) {
      log(
        `幸福请求接口[${url}]出错-${res.status} ${JSON.stringify(
          requestBody
        )} ${JSON.stringify(res.data)}`,
        'error'
      );
      if (res.data && res.data.code === 401) {
        // 登录态失效
        const tk = await this.handleLogin();
        if (!tk) {
          this.ticketUser.cinemaAccId &&
            (await API.authExpire(this.ticketUser.cinemaAccId));
          throw new Error('账号登录失败');
        } else {
          return this.requestPageApi(path, data, method);
        }
      }
      return res.data;
    }

    return res.data.data;
  }

  async handleLogin() {
    const tokenData = await this.requestPageApi(
      'auth/app/login',
      {
        username: this.ticketUser.cinemaAccount,
        password: this.ticketUser.cinemaAccountPwd,
      },
      'POST'
    );
    if (tokenData && tokenData.access_token) {
      this.loginToken = tokenData.access_token;
      // 更新数据库
      await API.updateLoginToken(
        this.ticketUser.cinemaAccId,
        tokenData.access_token
      );
      return this.loginToken;
    }
    return '';
  }

  // 订单回退
  async orderRollback(dataJson) {
    log('回调订单状态,出票失败');
    // 订单锁定取消
    await API.orderRollback(dataJson.id, dataJson.msg.substr(0, 100)).catch(
      (e) => console.error('取消订单请求异常', e)
    );
    if (this.orderConfirmId) {
      // 创建订单成功 付款失败
      const cancelRes = await this.cancelOrder();
      log(`取消订单:${this.orderConfirmId} ${JSON.stringify(cancelRes)}`);
    } else if (this.lockOrderId) {
      // 仅仅是座位锁定成功 订单取消锁定
      const unlockRes = await this.unlockSeat();
      log(`解锁座位:${this.lockOrderId} ${JSON.stringify(unlockRes)}`);
    }

    return true;
  }

  // 更新账户场次信息
  async updateShow(taskData) {
    // cinema_data: {"wapid": "XINGFU", "cinema": {"id": "", "name": "幸福蓝海（江宁店）", "linkid": "M100010023", "address": "南京市江宁区东山街道金箔路518号", "shortName": "", "permission": ""}, "linkid": "M100010023", "location": {"id": "320100", "name": "南京市"}}
    // 检查登录
    this.ticketUser = {
      cinemaAccId: taskData.account_id,
      cinemaAccount: taskData.account,
      cinemaAccountPwd: taskData.pwd,
    };

    const shows = await this.requestPageApi(
      `app/cinema/getShowListByCinemaCode?cinemaCode=${taskData.cinema_data.linkid}&channelCode=025000`,
      {},
      'POST'
    );
    if (!shows || !shows.films) {
      log('更新场次失败 ' + JSON.stringify(shows), 'error');
      await sleep(1000);
      return false;
    }

    const filmMap = {};
    for (const l of shows.films) {
      const filmName = l.filmName;
      if (!filmMap[filmName]) {
        filmMap[filmName] = [];
      }
      for (const filmChannelScheduleHall of l.filmChannelScheduleHalls) {
        for (const schedule of filmChannelScheduleHall.channelPlanList) {
          const showTime = timeFormat(new Date(schedule.showTime));
          filmMap[filmName].push({
            showTime,
            isSpec: ['IMAX', '4D', 'VIP'].some((w) =>
              schedule.screenName.includes(w)
            ),
            hallId: schedule.screenCode,
            scheduleKey: schedule.channelPlanCode,
            showNo: schedule.channelPlanCode,
            hallName: schedule.screenName,
            // displayPrice:
            //   schedule.salePrice > 0
            //     ? Math.round(
            //         schedule.salePrice * taskData['vip_cost_ratio'] * 100
            //       )
            //     : schedule.minMemberActivityPrice * 100, // 会员卡价格*系数
            displayPrice: schedule.minMemberActivityPrice * 100, // 会员卡价格
            originalStandardPrice: schedule.standardPrice * 100, // 标准价格
            standardPrice: schedule.listingPrice * 100, // 展示原价
            lowestPrice: schedule.lowestPrice * 100, // 发行价
            ticketFee: 0, // 影院手续费
          });
        }
      }
    }

    await API.updateShowlist(
      taskData.cinema_id,
      taskData.account_id,
      taskData.vip_price_status,
      filmMap
    );

    log(
      `${taskData['cinema_name']}[${taskData['cinemas_code']}] 场次数据更新成功[${taskData.account}]`
    );
  }

  // 更新院线
  async updateCinemas(taskData) {
    const allCitys = await this.requestPageApi(
      'app/city/getCityWithCinemaList'
    );
    const cityCinemasMap = [];
    for (const city of allCitys) {
      await sleep(100);
      const cinemas = await this.requestPageApi(
        `app/cinema/getCinemaList?cityCode=${city.cityCode}&pageNo=1&pageSize=100&sortType=0&channelCode=025000`
      );

      if (!cinemas || !Array.isArray(cinemas.records)) {
        log('更新院线失败 ' + JSON.stringify(cinemas), 'error');
        continue;
      }

      cinemas.records.forEach((ele) => {
        cityCinemasMap.push({
          address: ele.address,
          cityCode: city.cityCode,
          cityName: city.cityName,
          cinemaName: ele.cinemaName,
          cinemaLinkId: ele.cinemaCode,
        });
      });
    }
    await API.updateCinemasData(
      taskData.id,
      taskData.vip_price_status,
      cityCinemasMap
    );

    log(
      `${taskData['cinemas_name']}[${taskData['cinemas_code']}] 院线数据更新成功`
    );
  }
}
